<?php

namespace module\index\controller;

use app\Controller;
use app\model\Activity as Model;
use app\model\ActivityAlbum;
use app\model\ActivityEnroll;

class Activity extends Controller
{
    /**
     * 列表.
     * 
     */
    public function index()
    {
        $result = Model::withSearch(['status', 'title'], input('get.'))->field([
            'id', 'title', 'intro', 'origin_fee', 'fee', 'cover', 'tags', 'album_count',
        ])->paginate([
            'list_rows'=> input('get.pageSize/d', 10),
        ]);
        $items = $result->items();
        foreach($items as $k => $row){
            $items[$k]['discount_rate'] = sprintf("%.1f", $row->fee * 10 / $row->origin_fee);
        }
        return json([
            'items' => $items,
            'total' => $result->total()
        ]);
    }
    /**
     * 详情.
     * 
     * @param int $id
     */
    public function read(int $id)
    {
        $model = Model::with(['user', 'albums.learnLog' => function($query){
            $query->withField(['id', 'activity_id', 'title','is_try']);
        }])->field([
            'id', 'title', 'origin_fee', 'fee', 'cover', 'tags', 'intro', 'content', 'album_count' // 活动内容'
        ])->cache('Activity-' . $id, 60)->findOrFail($id);
        foreach($model->albums as $k => $row){
            $model->albums[$k]['learn_status'] = $row->status;
        }
        $model->discount_rate = sprintf("%.1f", $model->fee * 10 / $model->origin_fee);
        $model->collect = !UserEnroll::where('item_id', $id)->findOrEmpty()->isEmpty();
        return json($model->toArray());
    }
}
